package cn.fsw.pethome.org.service.impl;

import cn.fsw.pethome.base.service.impl.BaseServiceImpl;
import cn.fsw.pethome.org.domain.Department;
import cn.fsw.pethome.org.mapper.DepartmentMapper;
import cn.fsw.pethome.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper mapper;

    @Transactional
    @Override
    public void add(Department department) {
        mapper.add(department);
        this.update(department);
    }
    @Transactional
    @Override
    public void update(Department department) {
        if(department.getParent_id() == null){
            Long id = department.getId();
            department.setDirPath("/"+id);
        }else {
            Long parent_id = department.getParent_id();
            Department department1 = mapper.selectById(parent_id);
            String dirPath = department1.getDirPath();
            dirPath = dirPath+"/"+department.getId();
            department.setDirPath(dirPath);
        }
        mapper.update(department);
    }


    //批量删除
    @Transactional
    @Override
    public void batchDelete(List<Long> ids) {
        mapper.batchDelete(ids);
    }
    //部门树的实现
    @Override
    public List<Department> deptTree() {
        List<Department> departments = mapper.selectAll();
        List<Department> first = new ArrayList<>();
        for (Department department : departments) {
            if(department.getParent_id() == null){
                first.add(department);
            }else {
                for (Department department2 : departments) {
                    if(department.getParent_id() == department2.getId()){
                        department2.getChildren().add(department);
                    }
                }
            }
        }
        first.forEach(System.out::println);
        return first;

    }

}
